package com.yunpuvip.sachet.rest.common;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yunpuvip.sachet.biz.service.SysparamService;
import com.yunpuvip.sachet.rest.common.vo.WeChatUser;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@Lazy
public class WxTool {


    static final String LANG = "zh_CN";

    protected WxMpService wxMpService;


    @Autowired
    SysparamService sysparamService;



/**
     * 参考：https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
     * 微信小程序登录凭证校验
     *
     * @param jsCode
     * @return
     */

    /*public WeChatUser getOpenIdOfMini(String jsCode) {

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", sysparamService.loadSetting("miniAppID").getParamValue());
        paramMap.put("secret", sysparamService.loadSetting("miniAppSecret").getParamValue());
        paramMap.put("js_code", jsCode);
        paramMap.put("grant_type", "authorization_code");

        String content = HttpUtil.get(url, paramMap);

        log.info("WxUtil.getOpenId = " + content);
        JSONObject obj = JSONUtil.parseObj(content);
        if (obj.get("errcode") != null) {
            return null;
        }
//        if (StringUtils.isBlank(obj.get("errcode").toString())) {
//            return null;
//        }
        if (obj.get("openid") == null) {
            return null;
        }

        WeChatUser weChatUser = new WeChatUser();
        //  ....
        weChatUser.setSessionKey(obj.getStr("session_key"));
        weChatUser.setOpenId(obj.getStr("openid"));
        if (obj.get("unionid") != null) {
            weChatUser.setUnionid(obj.getStr("unionid"));
        } else {
            log.error("用户{} 无unionid");
        }

        return weChatUser;
    }
*/

    /**
     * 公众号获取用户信息
     *
     * @param accessToken accessToken
     * @param openId      openId
     * @return com.yunpuvip.sachet.modular.vo.rest.request.WeChatUser
     * @author hyf
     * @date 2019-03-19
     */

    public WeChatUser getWeChatUserInfo(String accessToken, String openId) {

        String url = "https://api.weixin.qq.com/sns/userinfo";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", accessToken);
        paramMap.put("openid", openId);
        paramMap.put("lang", "zh_CN");
        String content = HttpUtil.get(url, paramMap);

        log.info("微信h5获取用户信息= " + content);

        JSONObject obj = JSONUtil.parseObj(content);
        if (obj.get("errcode") != null) {
            log.error("获取用户信息失败");
            return null;
        }
        // URLEncoder.encode(line, "utf-8");
        WeChatUser weChatUser = new WeChatUser();
        weChatUser.setOpenId(obj.getStr("openid"));
        weChatUser.setNickname(obj.getStr("nickname"));
        weChatUser.setSex(obj.getInt("nickname"));
        weChatUser.setProvince(obj.getStr("province"));
        weChatUser.setCity(obj.getStr("city"));
        weChatUser.setCountry(obj.getStr("country"));
        weChatUser.setHeadimgurl(obj.getStr("headimgurl"));
        weChatUser.setUnionid(obj.getStr("unionid"));

        return weChatUser;
    }



/**
     * 获取微信公总号 openid
     *
     * @param code code
     * @return java.lang.String
     * @author hyf
     * @date 2019-03-08
     */

    public String getOpenId(String code) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.getWxMpOAuth2AccessToken(code);
        if (wxMpOAuth2AccessToken != null) {
            return wxMpOAuth2AccessToken.getOpenId();
        }
        return null;
    }


/**
     * 获取微信公总号 access_token
     *
     * @param code code
     * @return java.lang.String
     * @author hyf
     * @date 2019-03-08
     */

    public WxMpOAuth2AccessToken getWxMpOAuth2AccessToken(String code) {
        try {
            init();
            log.info("appid:{},秘钥:{}", sysparamService.loadSetting("AppID").getParamValue(), sysparamService.loadSetting("AppSecret").getParamValue());
            return this.wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("[getOpenId]:使用code换取openid 失败", e);
        }
        return null;
    }



/**
     * 通过openid  获取用户信息
     *
     * @param openid openid
     * @return me.chanjar.weixin.mp.bean.result.WxMpUser
     * @author hyf
     * @date 2019-03-08
     */

    public WxMpUser getUserInfo(String openid) {

        if (openid == null) {
            log.error("[getUserInfo]:使用openId获取用户信息 传入的openId为空");
            return null;
        }
        WxMpUser wxMpUser = null;
        try {
            init();
            wxMpUser = this.wxMpService.getUserService().userInfo(openid, LANG);

        } catch (WxErrorException e) {
            log.error("[getUserInfo]:使用openId获取用户信息 失败", e);
        }
        return wxMpUser;
    }


    public void init() {
        if (wxMpService != null) {
            log.info("wxMpService 第一次初始化");
            return;
        }
        WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
        configStorage.setAppId(sysparamService.loadSetting("AppID").getParamValue());
        configStorage.setSecret(sysparamService.loadSetting("AppSecret").getParamValue());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);

        this.wxMpService = wxMpService;
    }


    public WxJsapiSignature getJsapiSignature(String url) throws WxErrorException {
        init();
        WxJsapiSignature wxJsapiSignature = wxMpService.createJsapiSignature(url);
        System.out.println("微信分销秘钥:" + wxJsapiSignature.toString());
        return wxJsapiSignature;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(URLEncoder.encode("1啊爱上大所多", "utf-8"));
    }


}
